<template>
<div class="vip-setting views-container">
    <el-dialog :visible.sync="dialogVisibleImg" width="50%" custom-class="reset-pwd wlm-form-dialog dialog-table">
        <div class="wlm-form">
            <div class="wlm-form-header wlm-dialog-fixheader">
                <span class="wlm-dialog-inlenr" v-if="dialogUrl==1">虚拟人数</span>
                <span class="wlm-dialog-inlenr" v-if="dialogUrl==2">虚拟成本</span>
            </div>
            <div class="flex-row flex-justify-c" style="margin:20px 0">
                <el-scrollbar style="width:100%;height: 600px;max-height: 600px;overflow-x:hidden;">
                    <img style="width:44%" v-if="dialogUrl==1" src="@/assets/vip_card/ren.jpg" alt="">
                    <img style="width:44%" v-if="dialogUrl==2" src="@/assets/vip_card/qian.jpg" alt="">
                </el-scrollbar>
            </div>
        </div>
    </el-dialog>
    <div class="wlm-form">
        <div class="wlm-form-header">平台信息</div>
        <div class="wlm-form-content">
            <el-form ref="platform" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="180px" class="retail-form" label-position="right">
                <el-form-item label="是否开启会员卡">
                    <el-radio-group v-model="formFormatData.formData.is_open">
                        <el-radio label="1">开启</el-radio>
                        <el-radio label="2">关闭</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="会员卡名称">
                    <el-input v-model.trim="formFormatData.formData.card_title">
                    </el-input>
                </el-form-item>
                <el-form-item label="开通前背景">
                    <choose-files ref="chooseFilesBefore" :config="chooseLogoConfig" :changeEvt="formFormatFiltersChange"></choose-files>
                    <div v-if="!formFormatData.formData.image_first[0]" class="inline-block images-loader img-center" v-bind:style="{'background-image':`url(${require('@/assets/vip_card/vipgray.png')})`}"></div>
                    <div v-else class="inline-block images-loader img-center" v-bind:style="{'background-image':`url(${formFormatData.formData.image_first[0]['file_path']})`}"><i class="el-icon-close" @click="formFormatData.formData.image_first = []"></i></div>
                    <span @click="$refs.chooseFilesBefore.toggle()" class="inline-block flex-row flex-align-c flex-justify-c wlm-update-load"><i class="el-icon-plus avatar-uploader-icon"></i></span>
                    <div class="form-help">建议尺寸: 700*350像素</div>
                </el-form-item>
                   <el-form-item label="开通前描述">
                     <el-input
                        type="text"
                        placeholder="立享优惠折扣"
                        v-model="formFormatData.formData.card_describe_first"
                        maxlength="8"
                        show-word-limit
                      >
                     </el-input>
                   </el-form-item>
                    <el-form-item label="开通前按钮文案">
                     <el-input
                        type="text"
                        placeholder="立即开通"
                        v-model="formFormatData.formData.card_button_first"
                        maxlength="4"
                        show-word-limit
                      >
                     </el-input>
                   </el-form-item>
                <el-form-item label="开通后背景">
                    <choose-files ref="chooseFilesAfter" :config="chooseQrConfig" :changeEvt="formFormatFiltersChange"></choose-files>
                    <div v-if="!formFormatData.formData.image_second[0]" class="inline-block images-loader img-center" v-bind:style="{'background-image':`url(${require('@/assets/vip_card/vipblack.png')})`}"></div>
                    <div v-else class="inline-block images-loader img-center" v-bind:style="{'background-image':`url(${formFormatData.formData.image_second[0]['file_path']})`}"><i class="el-icon-close" @click="formFormatData.formData.image_second = []"></i></div>
                    <div @click="$refs.chooseFilesAfter.toggle()" class="inline-block flex-row flex-align-c flex-justify-c wlm-update-load"><i class="el-icon-plus avatar-uploader-icon"></i></div>
                    <div class="form-help">建议尺寸: 700*350像素</div>
                </el-form-item>
                <el-form-item label="开通后描述">
                     <el-input
                        type="text"
                        placeholder="立即续费，享受更多优惠！"
                        v-model="formFormatData.formData.card_describe_second"
                        maxlength="12"
                        show-word-limit
                      >
                     </el-input>
                   </el-form-item>
                     <el-form-item label="开通后按钮文案">
                     <el-input
                        type="text"
                        placeholder="立即续费"
                        v-model="formFormatData.formData.card_button_second"
                        maxlength="4"
                        show-word-limit
                      >
                     </el-input>
                   </el-form-item>
                <el-form-item label="虚拟人数">
                    <el-input @input.native="clearNativeReg(formFormatData.formData,'number')" width="50" v-model.trim="formFormatData.formData.number">
                        <template slot="append">人</template>
                    </el-input>
                    <div class="form-help">虚拟人数在用户端展示,用户营造气氛,刺激用户开通会员 <el-button @click="openDialog(1)" type="text">查看模板</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="虚拟成本">
                    <el-input @input.native="clearNativeReg(formFormatData.formData,'cost')" width="50" v-model="formFormatData.formData.cost">
                        <template slot="append">元</template>
                    </el-input>
                    <div class="form-help">虚拟成本在用户端展示,用户营造气氛,刺激用户开通会员 <el-button @click="openDialog(2)" type="text">查看模板</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="会员特权">
                    <choose-files ref="choosevipimg" :config="choosevipConfig" :changeEvt="formFormatFiltersChange"></choose-files>
                    <div v-if="!formFormatData.formData.image_third[0]" class="inline-block images-loader img-center" style="background-size: contain;" v-bind:style="{'background-image':`url(${require('@/assets/vip_card/vipPrivilege.png')})`}"></div>
                    <div v-else class="inline-block images-loader img-center" v-bind:style="{'background-image':`url(${formFormatData.formData.image_third[0]['file_path']})`}"><i class="el-icon-close" @click="formFormatData.formData.image_third = []"></i></div>
                    <span @click="$refs.choosevipimg.toggle()" class="inline-block flex-row flex-align-c flex-justify-c wlm-update-load"><i class="el-icon-plus avatar-uploader-icon"></i></span>
                </el-form-item>
            </el-form>
        </div>
    </div>

    <div class="wlm-form">
        <div class="wlm-form-header">其他设置</div>
        <div class="wlm-form-content table-content">
            <el-form ref="orther" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="180px" class="retail-form" label-position="right">
                <el-form-item label="是否开启激活码">
                    <el-radio-group v-model="formFormatData.formData.is_cdkey">
                        <el-radio label="1">开启</el-radio>
                        <el-radio label="2">关闭</el-radio>
                    </el-radio-group>
                    <div class="form-help">开启激活码后，用户端才展示兑换激活码入口</div>
                </el-form-item>
                <el-form-item label="会员专属优惠券">
                    <el-button type="primary" @click="couponToogle" style="display: block;margin: 12px 0;">添加优惠券</el-button>
                    <p class="form-help">优惠券仅可选择仅会员可领取的优惠券</p>
                    <choose-coupon ref="chooseCoupon" :config="chooseCouponConfig" :changeEvt="filtersCouponChange"></choose-coupon>

                    <el-table class="coupon-table" v-show="formFormatData.formData.coupon!=''" :data="formFormatData.formData.coupon" style="width: 100%;margin-top:20px;">
                        <el-table-column prop="date" label="优惠券名称">
                            <template slot-scope="scope">
                                <p>{{scope.row.name}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column prop="date" label="剩余库存">
                            <template slot-scope="scope">
                                <p>{{`${scope.row.total_num-scope.row.receive_num}`}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column prop="date" label="优惠券个数">
                            <template slot-scope="scope">
                                <div class="coupon-num-input">
                                    <el-input-number class="coupon-num-input" :controls="false" size="small" :min="0" :max="Number(scope.row.total_num) - Number(scope.row.receive_num)" v-model="scope.row.coupon_number"></el-input-number>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <div class="operation-group">
                                    <el-button class="wlm-text" type="text" @click="toggleSelection(scope)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="售卡模式">
                    <el-radio-group v-model="formFormatData.formData.buy_card_type">
                        <el-radio label="1">直接售卡</el-radio>
                        <el-radio label="2">购买商品赠送会员卡</el-radio>
                    </el-radio-group>
                    <choose-goods ref="chooseGoods" :config="chooseGoodsConfig" :changeEvt="filtersChange" ></choose-goods>
                    <el-button v-if="formFormatData.formData.buy_card_type=='2'" type="primary" @click="goodsToogle">添加商品</el-button>
                    <div class="form-help" style="margin-bottom:10px;">用户购买指定的商品后，自动成为相应会员，优惠券仅可选择仅会员可领取的优惠券</div>
                    <el-table class="goods-table" v-show="formFormatData.formData.goods!=''&&formFormatData.formData.buy_card_type=='2'" :data="formFormatData.formData.goods" row-key="goods_id" fit highlight-current-row style="width: 100%">
                        <el-table-column prop="date" label="拖拽" min-width="20">
                            <template slot-scope="scope">
                                <i class="el-icon-rank"></i>
                            </template>
                        </el-table-column>
                        <el-table-column prop="date" label="商品" min-width="100">
                            <template slot-scope="scope">
                                <div class="flex-row">
                                    <img class="logo" v-if="scope.row.img" :src="scope.row.img">
                                    <div class="inner-text flex-row flex-align-c">
                                        <p class="ellips_line2" style="width:200px;">{{scope.row.goods_name}}</p>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="date" label="选择会员卡">
                            <template slot-scope="scope">
                                <el-select v-model="scope.row.card_id" class="mincheck" placeholder="请选择">
                                    <el-option v-for="item in categoryData" :key="item.card_id" :label="item.card_title" :value="`${item.card_id}`">
                                    </el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="date" label="赠送优惠券">
                            <template slot-scope="scope">
                                <el-select clearable v-model="scope.row.coupon_id" class="mincheck" placeholder="请选择">
                                    <el-option v-for="item in couponData" :key="item.coupon_id" :label="item.name" :value="`${item.coupon_id}`">
                                    </el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="date" label="优惠券个数">
                            <template slot-scope="scope">
                                <div class="coupon-num-input">
                                    <el-input-number :disabled="!scope.row.coupon_id" class="coupon-num-input" :controls="false" size="small" :min="0" v-model="scope.row.coupon_number"></el-input-number>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <div class="operation-group">
                                    <el-button class="wlm-text" type="text" @click="deleteTable(scope)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <!-- <el-form-item label="非会员用户是否显示会员优惠">
                    <el-radio-group v-model="formFormatData.formData.un_preferential" style="margin-left:20px;">
                        <el-radio label="1">显示</el-radio>
                        <el-radio label="2">不显示</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="优惠">
                    <el-input placeholder="优惠" maxlength="2" v-model="formFormatData.formData.discount_font">
                    </el-input>
                    <p class="form-help">最多输入2个字</p>
                </el-form-item>
                <el-form-item label="会员">
                    <el-input placeholder="会员" maxlength="2" v-model="formFormatData.formData.member_font">
                    </el-input>
                    <p class="form-help">最多输入2个字</p>
                </el-form-item>
                <el-form-item label="专享">
                    <el-input placeholder="专享" maxlength="2" v-model="formFormatData.formData.exclusive_font">
                    </el-input>
                    <p class="form-help">最多输入2个字</p>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <div class="wlm-form">
        <div class="wlm-form-header">分享设置</div>
        <div class="wlm-form-content">
            <el-form ref="platform" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="180px" class="retail-form" label-position="right">
                <el-form-item label="标题">
                    <el-input v-model="formFormatData.formData.setting.member_title">
                    </el-input>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 4}" v-model="formFormatData.formData.setting.member_describe">
                    </el-input>
                </el-form-item>
                <el-form-item label="封面图">
                    <choose-files ref="chooseFiles" :config="imgCAConfig" :changeEvt="formFormatFiltersChange"></choose-files>
                    <p class="form-help">大小2M以下,建议尺寸200×200px</p>
                </el-form-item>
                <el-form-item label="小程序封面图">
                    <choose-files ref="chooseFiles" :config="imgCBConfig" :changeEvt="formFormatFiltersChange"></choose-files>
                    <p class="form-help">大小2M以下,建议尺寸500×400px</p>
                </el-form-item>
                <el-form-item label="分享页面背景图">
                    <choose-files ref="chooseFiles" :config="imgCCConfig" :changeEvt="formFormatFiltersChange"></choose-files>
                    <p class="form-help">建议尺寸750×1300px</p>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <div v-cloak class="wlm-fixed-btn flex-row flex-align-c flex-justify-c">
        <el-button size="small" @click="saveForm" type="primary">保存</el-button>
    </div>
</div>
</template>

<script>
import ChooseFiles from '@/components/ChooseFiles/index'
import ChooseGoods from '@/components/ChooseGoods/index'
import ChooseCoupon from '@/components/ChooseCoupon/index'
import Sortable from 'sortablejs'
import {
  cardGet,
  cardSave,
  selectedCard,
  memberCoupon
} from '@/api/application'
import mixins from '@/mixins/mixins'
export default {
  mixins: [mixins.getters('Form')],
  name: 'ManagementUserAdd',
  components: {
    ChooseFiles,
    ChooseGoods,
    ChooseCoupon,
    couponRender: {
      template: '<span><slot name="title"></slot><span class="text-danger"><slot name="price"></slot></span><slot name="tail"></slot></span>'
    }
  },
  directives: {},
  created() {
    this.$nextTick(() => {
      // if (this.formFormatData.formData.goods !== '') {
      this.goodsListGrag()
      // }
      // if (this.formFormatData.formData.coupon !== '') {
      // this.goodsCouponGrag()
      // }
      selectedCard().then((response) => {
        const {
          data: {
            data: msgData = []
          }
        } = response
        this.categoryData = msgData
      })
      memberCoupon().then((response) => {
        const {
          data: {
            data: msgData = []
          }
        } = response
        const result = []
        msgData.map(item => {
          const { coupon_id, name } = item
          result.push({ coupon_id, name })
        })
        this.couponData = result
        console.log(this.couponData)
      })
    })
  },
  data() {
    return {
      newGoodsList: [],
      oldGoodsList: [],
      newCouponList: [],
      oldCouponList: [],
      dialogUrl: 1,
      dialogVisibleImg: false,
      couponData: [],
      categoryData: [],
      defaultMsg: '',
      currentRow: [],
      couponCurrentRow: [],
      imgCAConfig: {
        type: ['image'],
        model: 'display',
        uploadConfig: {
          limit: 1,
          model: 'display'
        },
        isUnique: true,
        initList: [],
        isShowList: true,
        file_type: 'image',
        bindKey: {
          key: 'setting|member_cover_image',
          model: 'img'
        }
      },
      imgCBConfig: {
        type: ['image'],
        model: 'display',
        uploadConfig: {
          limit: 1,
          model: 'display'
        },
        isUnique: true,
        initList: [],
        isShowList: true,
        file_type: 'image',
        bindKey: {
          key: 'setting|member_app_image',
          model: 'img'
        }
      },
      imgCCConfig: {
        type: ['image'],
        model: 'display',
        uploadConfig: {
          limit: 1,
          model: 'display'
        },
        isUnique: true,
        initList: [],
        isShowList: true,
        file_type: 'image',
        bindKey: {
          key: 'setting|member_back_image',
          model: 'img'
        }
      },
      chooseGoodsConfig: {
        type: ['chooseGoods'],
        model: 'normal',
        initList: [],
        keys: 'keyrow',
        disabled: [{
          label: 'spec_type',
          value: 20
        }]
      },
      chooseCouponConfig: {
        type: ['chooseCoupon'],
        model: 'display',
        get_limit_type: 1,
        disabled: [{
          label: 'status',
          value: 1,
          reverse: true
        },
        {
          label: 'get_limit_type',
          value: 1,
          reverse: true
        }],
        initList: []
      },
      chooseLogoConfig: {
        type: ['image'],
        model: 'normal',
        uploadConfig: {
          limit: 1,
          isMore: false,
          model: 'normal'
        },
        initList: [],
        file_type: 'image',
        bindKey: {
          key: 'image_first',
          model: 'img'
        }
      },
      chooseQrConfig: {
        type: ['image'],
        model: 'normal',
        uploadConfig: {
          limit: 1,
          isMore: false,
          model: 'normal'
        },
        initList: [],
        file_type: 'image',
        bindKey: {
          key: 'image_second',
          model: 'img'
        }
      },
      choosevipConfig: {
        type: ['image'],
        model: 'normal',
        uploadConfig: {
          limit: 1,
          isMore: false,
          model: 'normal'
        },
        initList: [],
        file_type: 'image',
        bindKey: {
          key: 'image_third',
          model: 'img'
        }
      },
      formFormatData: {
        key: ['platform', 'orther'],
        api: {
          editForm: {
            api: cardGet,
            params: {
              always: true
            }
          },
          submitForm: cardSave
        },
        formData: {
          card_title: '',
          is_open: '1',
          // un_preferential:'1',
          setting: {
            member_title: '',
            member_describe: '',
            member_cover_image: [],
            member_app_image: [],
            member_back_image: []
          },
          discount_font: '',
          member_font: '',
          exclusive_font: '',
          image_first: [],
          card_describe_first:'',
          card_describe_second:'',
          card_button_first:'',
          card_button_second:'',
          image_second: [],
          image_third: [],
          number: '',
          cost: '',
          content: '',
          is_cdkey: '2',
          buy_card_type: '1',
          goods: [],
          coupon: []
        },
        rules: {}
      }
    }
  },
  mounted() {

  },
  methods: {
    openDialog(data) {
      if (data === 1) {
        this.dialogUrl = 1
      } else {
        this.dialogUrl = 2
      }
      this.dialogVisibleImg = true
    },
    serverInfoChange(msg) {
      this.defaultMsg = msg
    },
    formFormatCallBack(data, type, response) {
      if (type === 'editForm') {
        const { content, setting } = data
        this.defaultMsg = content
        this.imgCAConfig.initList = setting.member_cover_image
        this.imgCBConfig.initList = setting.member_app_image
        this.imgCCConfig.initList = setting.member_back_image
      }
    },
    saveForm() {
      // 保存到你要的那个form值里面
      this.formFormatData.formData.content = this.defaultMsg
      this.formFormatSubmit()
    },
    filtersChange(val) {
      this.currentRow = val.currentRow
      const displayData = val.displayData
      console.log(this.formFormatData.formData)
      displayData.map(item => {
        var hasIndex = this.formFormatData.formData.goods.findIndex(tableitem => { return `${tableitem.goods_id}` === `${item.goods_id}` })
        if (hasIndex === -1) {
          this.formFormatData.formData.goods.push({ goods_id: item.goods_id, goods_name: item.goods_name, img: item.image[0]['file_path'] })
        }
      })
    },
    goodsListGrag() {
      // newGoodsList:[],
      // oldGoodsList:[],
      this.oldGoodsList = this.formFormatData.formData.goods.map(v => v.goods_id)
      this.newGoodsList = this.oldGoodsList.slice()
      this.$nextTick(() => {
        this.setSort()
      })
    },
    goodsCouponGrag() {
      // newCouponList:[],
      // oldCouponList:[],
      this.oldCouponList = this.formFormatData.formData.coupon.map(v => v.coupon_id)
      this.newCouponList = this.oldCouponList.slice()
      this.$nextTick(() => {
        this.setSortCopon()
      })
    },
    setSortCopon() {
      const el = document.querySelectorAll('.wlm-form .wlm-form-content.table-content .el-form-item__content .coupon-table .el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.formFormatData.formData.coupon.splice(evt.oldIndex, 1)[0]
          this.formFormatData.formData.coupon.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newCouponList.splice(evt.oldIndex, 1)[0]
          this.newCouponList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    },
    setSort() {
      console.log('setSort')
      const el = document.querySelectorAll('.wlm-form .wlm-form-content.table-content .el-form-item__content .goods-table .el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.formFormatData.formData.goods.splice(evt.oldIndex, 1)[0]
          this.formFormatData.formData.goods.splice(evt.newIndex, 0, targetRow)
          const tempIndex = this.newGoodsList.splice(evt.oldIndex, 1)[0]
          this.newGoodsList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    },
    filtersCouponChange(arg) {
      const { currentRow, displayData } = arg
      this.couponCurrentRow = currentRow
      displayData.map(item => {
        var hasIndex = this.formFormatData.formData.coupon.findIndex(tableitem => { return `${tableitem.coupon_id}` === `${item.coupon_id}` })
        console.log(hasIndex, this.formFormatData.formData.coupon)
        if (hasIndex === -1) {
          this.formFormatData.formData.coupon.push({ coupon_type: item.coupon_type, name: item.name, total_num: item.total_num, receive_num: item.receive_num, coupon_id: item.coupon_id, coupon_number: item.coupon_number })
        }
      })
    },
    goodsToogle() {
      const result = []
      this.formFormatData.formData.goods.map(item => {
        result.push(item.goods_id)
      })
      this.$refs.chooseGoods.currentRow = result
      this.$refs.chooseGoods.toggle()
    },
    couponToogle() {
      this.$refs.chooseCoupon.currentRow = this.couponCurrentRow
      this.$refs.chooseCoupon.toggle()
    },
    deleteTable(scope) {
      this.formFormatData.formData.goods.splice(scope.$index, 1)
      this.currentRow.splice(scope.$index, 1)
    },
    toggleSelection(scope) {
      this.formFormatData.formData.coupon.splice(scope.$index, 1)
      this.currentRow.splice(scope.$index, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.vip-setting {
    /deep/ .sortable-ghost {
        opacity: .8;
        color: #fff !important;
        background: #79bbff !important;
    }

    /deep/ .mincheck .el-input {
        width: 220px;
    }

    /deep/ .el-scrollbar__wrap {
        overflow-x: hidden;

        /deep/ .el-scrollbar__view {
            text-align: center;
        }
    }

    /deep/ .el-input-number .el-input__inner {
        text-align: left !important;
    }

    .images-loader {
        position: relative;
        width: 200px;
        height: 100px;
        border-radius: 5px;
        vertical-align: middle;
        margin-right: 20px;

        .el-icon-close {
            position: absolute;
            cursor: pointer;
            right: 5px;
            top: 5px;
        }
    }

    .wlm-update-load {
        vertical-align: middle;
    }

    /deep/ .coupon-num-input .el-input,
    .el-input-number {
        width: 170px;
    }

    .logo {
        height: 40px;
        width: 40px;
        border-radius: 50%;
        vertical-align: middle;
        margin-right: 6px;
    }
}
</style>
